package com.yincheng.oes.business.schedule;

import com.yincheng.oes.attachment.mapper.AttachmentMapper;
import com.yincheng.oes.business.util.ExportFileUtils;
import com.yincheng.oes.business.util.TimeUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.TimerTask;

/**
 * @Description 清除过期的临时文件
 * @Author 446948434@qq.com
 * @Date 2021/11/6 1:30 下午
 * @Version 1.0
 */
@Component
public class CleanTmpFileTask extends TimerTask {

    /**
     * 日志
     */
    private static final Logger logger = LogManager.getLogger(CleanTmpFileTask.class);

    private static final long DAYS = 3L;

    private static final String YYMMdd = "yyyyMMdd";

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Override
    public void run() {
        try {
            // 清理临时文件
            deleteTmpDirectories();

            // 清理临时文件mysql数据
            deleteTmpFileData();
        } catch (Exception e) {
            logger.error("delete temp file error!", e);
        }
    }

    private void deleteTmpFileData() {
        LocalDate now = LocalDate.parse(TimeUtils.getYYMMdd(), DateTimeFormatter.ofPattern(YYMMdd));
        LocalDate localDate = now.minusDays(DAYS);
        int num = attachmentMapper.deleteTmpFile(TimeUtils.localDate2Date(localDate));
        logger.debug("delete temp file in db success, count is {}", num);
    }

    private void deleteTmpDirectories() {
        logger.debug("start delete tmp files");
        ExportFileUtils.getTmpPath();
        File tempFileDir = FileUtils.getFile(ExportFileUtils.getTmpPath());
        List<File> deleteDirs = new ArrayList<>();
        if (tempFileDir.isDirectory() && ArrayUtils.isNotEmpty(tempFileDir.listFiles())) {
            File[] files = tempFileDir.listFiles();
            for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
                if (isNeedDelete(files[i].getName())) {
                    deleteDirs.add(Objects.requireNonNull(files)[i]);
                }
            }
        }
        logger.debug("delete tmp fileDirs size is {}", CollectionUtils.size(deleteDirs));
        for (File deleteDir : deleteDirs) {
            recursiveDelete(deleteDir);
        }

    }

    private void recursiveDelete(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                for (File listFile : Objects.requireNonNull(file.listFiles())) {
                    recursiveDelete(listFile);
                }
            }
            file.delete();
        }
    }

    private boolean isNeedDelete(String dirName) {
        try {
            LocalDate dirDate = LocalDate.parse(dirName, DateTimeFormatter.ofPattern(YYMMdd));
            LocalDate now = LocalDate.now();
            if (ChronoUnit.DAYS.between(dirDate, now) > DAYS) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

}
